<?php
namespace Modules\Wachat\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Modules\Wachat\Entities\Wxmenu;
use Modules\Wachat\Http\Requests\WxmenuRequest;
class WxmenuController extends Controller
{
    //显示列表
    public function index()
    {
        $data = Wxmenu::paginate(10);
        return view('wachat::wxmenu.index', compact('data'));
    }

    //创建视图
    public function create(Wxmenu $wxmenu)
    {
        return view('wachat::wxmenu.create',compact('wxmenu'));
    }

    //保存数据
    public function store(WxmenuRequest $request, Wxmenu $wxmenu)
    {
        $post = $request->all();
        //$post['data'] = json_decode($post['data'],true);
        $wxmenu->fill($post);
        $wxmenu->save();

        return redirect('/wachat/wxmenu')->with('success', '保存成功');
    }

    //显示记录
    public function show(Wxmenu $field)
    {
        return view('wachat::wxmenu.show', compact('field'));
    }

    //编辑视图
    public function edit(Wxmenu $wxmenu)
    {
        return view('wachat::wxmenu.edit', compact('wxmenu'));
    }

    //更新数据
    public function update(WxmenuRequest $request, Wxmenu $wxmenu)
    {
        $post = $request->all();
        //$post['data'] = json_decode($post['data'],true);
        $wxmenu->update($post);
        return redirect('/wachat/wxmenu')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Wxmenu $wxmenu)
    {
        $wxmenu->delete();
        return redirect('wachat/wxmenu')->with('success','删除成功');
    }

    public function push(Wxmenu $wxmenu,WechatService $wechatService){
        //将需要推送的数据中的data的值改成php
        $data['button'] = json_decode($wxmenu['data'],true);
        //调用wechat类里面的创建自定义菜单方法,来向微信服务器发请求,帮我们创建需要的菜单
        //调用创建菜单之前,需要设置配置项
        //['button' => json_decode($wxmenu['data'],true)]
        $res = $wechatService->instance('button')->create($data);
        //$res = WeChat::instance('button')->create(['button' => $wx_menu['data']]);
        if ($res['errcode'] == 0){
            return back()->with('success','自定义菜单推送到微信成功,请打开手机微信公众号查看');
        }
        return back()->with('danger',$res['errmsg']);
    }
}
